package com.sqtracker.recommender.scheduler;

import com.sqtracker.recommender.algorithm.ContentBasedRecommender;
import com.sqtracker.recommender.algorithm.ItemCFRecommender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 推荐相关定时任务
 */
@Component
public class RecommendationScheduler {

    private static final Logger logger = LoggerFactory.getLogger(RecommendationScheduler.class);

    private final ItemCFRecommender itemCFRecommender;
    private final ContentBasedRecommender contentBasedRecommender;

    @Autowired
    public RecommendationScheduler(
            ItemCFRecommender itemCFRecommender,
            ContentBasedRecommender contentBasedRecommender) {
        this.itemCFRecommender = itemCFRecommender;
        this.contentBasedRecommender = contentBasedRecommender;
    }

    /**
     * 更新物品相似度矩阵
     * 默认每3小时执行一次
     */
    @Scheduled(cron = "${recommendation.schedule.precompute-cron:0 0 */3 * * *}")
    public void updateItemSimilarityMatrix() {
        try {
            logger.info("开始更新物品相似度矩阵...");
            long startTime = System.currentTimeMillis();

            itemCFRecommender.computeItemSimilarityMatrix();

            long endTime = System.currentTimeMillis();
            logger.info("物品相似度矩阵更新完成，耗时: {} ms", endTime - startTime);
        } catch (Exception e) {
            logger.error("更新物品相似度矩阵失败", e);
        }
    }

    /**
     * 清理内容推荐缓存
     * 每天凌晨3点执行
     */
    @Scheduled(cron = "0 0 3 * * *")
    public void clearContentRecommenderCache() {
        try {
            logger.info("开始清理内容推荐缓存...");

            contentBasedRecommender.clearVectorCache();

            logger.info("内容推荐缓存清理完成");
        } catch (Exception e) {
            logger.error("清理内容推荐缓存失败", e);
        }
    }

    /**
     * 更新推荐统计数据
     * 每天凌晨2点执行
     */
    @Scheduled(cron = "0 0 2 * * *")
    public void updateRecommendationStats() {
        try {
            logger.info("开始更新推荐统计数据...");

            // TODO: 实现推荐统计逻辑

            logger.info("推荐统计数据更新完成");
        } catch (Exception e) {
            logger.error("更新推荐统计数据失败", e);
        }
    }
}